﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Gis;
using Aspose.Gis.Geometries;
using System.IO;
using System.Reflection;

namespace ZhZyz.Gdal
{
    public class MyGDBHelper
    {
        public delegate void ProcessEventHandle(string msg);
        public static event ProcessEventHandle ProcessEvent;

        /// <summary>
        ///     添加数据
        /// </summary>
        /// <param name="datafile">数据文件路径</param>
        /// <param name="layerName">图层</param>
        /// <param name="geojsons">json格式</param>
        public static void AppendData(string datafile, string layerName, string[] geojsons)
        {
            if (geojsons.Length == 0) return;
            var jo = JObject.Parse(geojsons[0]);
         

            using (var dataSource = OpenDataSource(datafile))
            using (var layer = GetLayer(dataSource, layerName,  out bool isNew))
            {

                if (isNew)
                {
                    //添加字段
                    foreach (var item in jo["properties"])
                    {

                        JProperty property = (JProperty)item;

                        layer.Attributes.Add(new FeatureAttribute(property.Name, AttributeDataType.String));

                    }

                }

                //添加要素
                foreach (var item in geojsons)
                {
                    jo = JObject.Parse(item);
                    var geojs = jo["geometry"];
                    Feature feature = layer.ConstructFeature();
                    foreach (var item1 in jo["properties"])
                    {
                        JProperty property = (JProperty)item1;
                        feature.SetValue<string>(property.Name, property.Value.ToString());
                    }
                    feature.Geometry = Geometry.FromText(geojs.ToString());
                    // var geo = Ogr.CreateGeometryFromJson(geojs.ToString());
                    
                    layer.Add(feature);
                }
            }

        }
        /// <summary>
        ///     添加数据
        /// </summary>
        /// <param name="datafile">数据文件路径</param>
        /// <param name="layerName">图层</param>
        /// <param name="geojsons">json格式</param>
        public static void AppendData(string datafile, string layerName, string geofile)
        {


            using (var dataSource = OpenDataSource(datafile))
            using (var layer = GetLayer(dataSource, layerName, out bool isNew))
            {
                var prestr = layerName.EndsWith("pt")||layerName.EndsWith("ao") ? "POINT" : layerName.EndsWith("pl") ? "LINESTRING" : "POLYGON";
                StreamReader sr = new StreamReader(geofile);
                var sl = sr.ReadLine();
                int k = 0;
                while (!string.IsNullOrWhiteSpace(sl))
                {
                    var jo = JObject.Parse(sl);
                    if (isNew && k == 0)
                    {
                        //添加字段
                        foreach (var item in jo["properties"])
                        {

                            JProperty property = (JProperty)item;

                            layer.Attributes.Add(new FeatureAttribute(property.Name, AttributeDataType.String));

                        }
                      

                    }

                    //添加要素
                    
                    var geojs = jo["geometry"];
                    if(geojs.Value<string>()!=null && geojs.Value<string>().StartsWith(prestr))
                    {
                        Feature feature = layer.ConstructFeature();

                        foreach (var item1 in jo["properties"])
                        {
                            JProperty property = (JProperty)item1;
                            if (layer.Attributes.Contains(property.Name))
                                feature.SetValue<string>(property.Name, property.Value.ToString());
                        }
                        feature.Geometry = Geometry.FromText(geojs.ToString());
                        layer.Add(feature);
                    }
                  
                    k++;
                    sl = sr.ReadLine();
                }
                sr.Close();
            }

        }
        public static void CreateDatas(string datafile)
        {
            var outpath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            string[] files = Directory.GetFiles(outpath, "*.gkt");
            foreach (var f in files)
            {
                ProcessEvent($"正在将{Path.GetFileName(f)}写入数据库。。\r\n");
                AppendData(datafile, Path.GetFileNameWithoutExtension(f), f);
                //string[] gfs = File.ReadAllLines(f);
                //AppendData(datafile, Path.GetFileNameWithoutExtension(f), gfs);
                File.Delete(f);
            }
            ProcessEvent($"*****写入完成{DateTime.Now.ToShortTimeString()}*****\r\n");
        }

        private static VectorLayer GetLayer(Dataset dataSource, string layerName,  out bool isNew)
        {
            isNew = false;
            VectorLayer layer = null;
            for (int i = 0; i < dataSource.LayersCount; i++)
            {
                
                if (dataSource.GetLayerName(i).Equals(layerName, StringComparison.InvariantCultureIgnoreCase))
                {
                    layer = dataSource.EditLayer(layerName);
                    
                }
            }

 
            if (layer == null)
            {
                isNew = true;
                layer = dataSource.CreateLayer(layerName);
                
            }    

          
               
            return layer;
        }

        private static Dataset OpenDataSource(string datafile)
        {
    
            return System.IO.Directory.Exists(datafile) ? Dataset.Open(datafile,Drivers.FileGdb) : Dataset.Create(datafile, Drivers.FileGdb);

        }
    }
}
